import React, { useEffect } from 'react'
import type { FC } from 'react'
import * as echarts from 'echarts'
import { throttle } from './tools'

type ISeries = {
  // data: number[]
  data: unknown
  name?: string
  type?: 'line'
  smooth?: boolean
  // 动态属性 对象索引
  [prop: string]: any
}[]

interface IProps {
  height?: number
  xdata: string[]
  series: ISeries
}

const MyLine: FC<IProps> = ({ xdata, series, height = 300 }) => {
  let myChart: echarts.ECharts
  useEffect(() => {
    let seriesData = series.map((item) => {
      return {
        ...item,
        data: item.data as number[],
        type: 'line'
      }
    })
    let chartDom = document.getElementById('line-main')
    myChart = echarts.init(chartDom)
    myChart.setOption({
      tooltip: {},
      xAxis: {
        type: 'category',
        data: xdata,
        boundaryGap: false
        // splitLine: {
        //   show: false
        // }
      },
      yAxis: {
        type: 'value'
        // splitLine: {
        //   show: false
        // }
      },
      grid: {
        left: 45,
        right: 10,
        top: 10,
        bottom: 25
      },
      series: seriesData
    })
    return () => {
      // 离开当前页面时，销毁所有的对象
      myChart.dispose()
      chartDom = null
      myChart = null as any
    }
  }, [])

  // 监听窗口变化，重新渲染
  const resetWin = throttle(() => {
    if (myChart != null && myChart != undefined) {
      myChart.resize()
    }
  })

  useEffect(() => {
    window.addEventListener('resize', resetWin)
    return () => {
      window.removeEventListener('resize', resetWin)
    }
  }, [])

  return <div id="line-main" style={{ width: '100%', height }}></div>
}

export default MyLine
